package com.custom.base.util

import android.content.res.Resources
import android.graphics.*
import java.io.*
import java.nio.ByteBuffer
import kotlin.math.ln
import kotlin.math.pow
import kotlin.math.roundToInt

/**
 * 作者：
 * 日期：2020-12-19
 * 说明：
 */
class BitMapUtil {
    private val lock = Any()
    /**
     * BitMap转byte数组
     * @param b Bitmap
     */
    fun bmpToByteArray(bmp: Bitmap, needRecycle: Boolean): ByteArray? {
        var i: Int
        var j: Int
        if (bmp.height > bmp.width) {
            i = bmp.width
            j = bmp.width
        } else {
            i = bmp.height
            j = bmp.height
        }
        val localBitmap = Bitmap.createBitmap(i, j, Bitmap.Config.RGB_565)
        val localCanvas = Canvas(localBitmap)
        while (true) {
            localCanvas.drawBitmap(bmp, Rect(0, 0, i, j), Rect(0, 0, i, j), null)
            if (needRecycle) bmp.recycle()
            val localByteArrayOutputStream = ByteArrayOutputStream()
            localBitmap.compress(
                Bitmap.CompressFormat.JPEG, 100,
                localByteArrayOutputStream
            )
            localBitmap.recycle()
            val arrayOfByte = localByteArrayOutputStream.toByteArray()
            try {
                localByteArrayOutputStream.close()
                return arrayOfByte
            } catch (e: Exception) {
                //F.out(e);
            }
            i = bmp.height
            j = bmp.height
        }
    }
    fun decodeByteArray(data: ByteArray): Bitmap? {
        synchronized(lock) {
            val options = BitmapFactory.Options()
            options.inPurgeable = true
            options.inInputShareable = true
            return try {
                BitmapFactory.decodeByteArray(data, 0, data.size, options)
            } catch (e: Throwable) {
                null
            }
        }
    }
    fun decodeResource(res: Resources?, resId: Int): Bitmap? {
        synchronized(lock) {
            val options = BitmapFactory.Options()
            options.inPurgeable = true
            options.inInputShareable = true
            return try {
                BitmapFactory.decodeResource(res, resId, options)
            } catch (e: Throwable) {
                null
            }
        }
    }
    /**
     * 根据 路径 得到 file 得到 bitmap
     * @param filePath 本地路径
     */
    @Throws(IOException::class)
    fun decodeFiles(filePath: String?): Bitmap? {
        var b: Bitmap? = null
        val IMAGE_MAX_SIZE = 600
        val f = File(filePath) ?: return null
        //Decode image size
        val o = BitmapFactory.Options()
        o.inJustDecodeBounds = true
        var fis = FileInputStream(f)
        BitmapFactory.decodeStream(fis, null, o)
        fis.close()
        var scale = 1
        if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
            scale = 2.0.pow((ln(IMAGE_MAX_SIZE / o.outHeight.coerceAtLeast(o.outWidth).toDouble()) / ln(0.5)).roundToInt().toDouble()).toInt()
        }

        //Decode with inSampleSize
        val o2 = BitmapFactory.Options()
        o2.inSampleSize = scale
        fis = FileInputStream(f)
        b = BitmapFactory.decodeStream(fis, null, o2)
        fis.close()
        return b
    }
    fun getBitmapThumbnail(path: String,  sampleSize: Int): Bitmap? {
        //这里可以按比例缩小图片：
        val opts = BitmapFactory.Options()
        opts.inSampleSize = sampleSize//宽和高都是原来的1/4
        return BitmapFactory.decodeFile(path, opts)
    }
    fun getBitmapThumbnail(path: String, width: Int, height: Int): Bitmap? {
        val opts = BitmapFactory.Options()
        opts.inJustDecodeBounds = true
        BitmapFactory.decodeFile(path, opts)
        opts.inSampleSize = (opts.outHeight / height.toFloat()).toInt().coerceAtLeast((opts.outWidth / width.toFloat()).toInt())
        opts.inJustDecodeBounds = false
        return BitmapFactory.decodeFile(path, opts)
    }

    fun getBitmapThumbnail(bmp: Bitmap?, width: Int, height: Int): Bitmap? {
        var bitmap: Bitmap? = null
        if (bmp != null) {
            val bmpWidth = bmp.width
            val bmpHeight = bmp.height
            bitmap = if (width != 0 && height != 0) {
                val matrix = Matrix()
                val scaleWidth = width.toFloat() / bmpWidth
                val scaleHeight = height.toFloat() / bmpHeight
                matrix.postScale(scaleWidth, scaleHeight)
                Bitmap.createBitmap(bmp, 0, 0, bmpWidth, bmpHeight, matrix, true)
            } else {
                bmp
            }
        }
        return bitmap
    }
    //Bitmap对象保存味图片文件
    fun saveBitmapFile(bitmap: Bitmap, path: String?): File? {
        val file = File(path) //将要保存图片的路径
        try {
            val bos = BufferedOutputStream(FileOutputStream(file))
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos)
            bos.flush()
            bos.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return file
    }
}